﻿using System;
using System.Collections.Generic;
using IrrlichtLime;
using IrrlichtLime.Core;
using Timed;
using IrrlichtLime.Scene;
using IrrlichtLime.Video;
using LuaInterface;
using Iso.Common;

namespace Iso.Core
{
    public class FieldNPC
    {
        public AnimatedSprite sprite;
        public string updateFunction, actionButtonFunction;

        string lastAnimName, nextAnimName;
        bool buttonPressed = false;
        public float distanceTrigger = 7;

        public FieldNPC(AnimatedSprite sprite, string updateFunction, string actionButtonFunction)
        {
            this.sprite = sprite;
            this.updateFunction = updateFunction;
            this.actionButtonFunction = actionButtonFunction;

            // Initial Animation (needed)
            sprite.SetAnimation("NS");
        }

        public void Update(Vector3Df pos)
        {
            sprite.Update();
            if (sprite.isFinished && lastAnimName != nextAnimName && nextAnimName != "")
            {
                lastAnimName = nextAnimName;
                nextAnimName = "";
                sprite.SetAnimation(lastAnimName);
            }

            if (updateFunction != "")
                Engine.lua.GetFunction(updateFunction).Call(sprite);

            if (actionButtonFunction != "")
            {
                Vector3Df position = sprite.sceneNode.Position;
                if (Keyboard.IsKeyDown(KeyCode.Return))
                {
                    if ((pos.X < position.X + distanceTrigger && pos.X > position.X - distanceTrigger) &&
                        (pos.Y < position.Y + distanceTrigger && pos.Y > position.Y - distanceTrigger) &&
                        (pos.Z < position.Z + distanceTrigger && pos.Z > position.Z - distanceTrigger) && !buttonPressed)
                    {
                        Engine.lua.GetFunction(actionButtonFunction).Call(sprite);
                    }
                    buttonPressed = true;
                }
                else
                    buttonPressed = false; 
            }
        }

        public void Animate(string animName)
        {
            nextAnimName = animName;
        }

        public void Remove()
        {
            sprite.Remove();
        }
    }
}
